package com.ls.myRealm;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.ls.bean.Account;
import com.ls.service.UserServiceImp;

/**
 * realm实体类
 * 
 * @author gym
 * @date 2017.12.15
 * @version 1.0
 *
 */

public class MyRealm extends AuthorizingRealm{

	@Autowired
	private UserServiceImp userServiceImp;
	
	//二、用户授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		System.out.println("in realm doGetAuthorizationInfo");
		
		//1.获得当前登陆对象名
		 Account account=(Account) principals.getPrimaryPrincipal(); 
		 System.out.println("name:"+account.getUserName());
		 
		 //2.获取数据库信息 获得 permissions
	     Set<String> set=userServiceImp.getAccountPer(account.getUserName()); 
	     System.out.println("++set++"+set.toString());
	     //3.授权认证   
	    SimpleAuthorizationInfo  authorizationInfo=new SimpleAuthorizationInfo(); 
	    authorizationInfo.setStringPermissions(set);  
	    
	        return authorizationInfo; 
	}

	
	//一.用户认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		System.out.println("in realm doGetAuthenticationInfo");
		// TODO Auto-generated method stub
		//1.获取用户名
		 String username=(String) token.getPrincipal(); 
		 System.out.println("准备搜库"+username);
	    //2.根据登陆的用户名去数据库中查找该用户是否存在，不存在返回null 报runtimeException 
		 Account account=userServiceImp.getAccountByName(username);
		 System.out.println("从数据库中返回"+account);
		//3.如果用户存在则验证用户密码
	        if(account!=null){  
	        	//入参写入数据库查的用户名和密码即可与token令牌中的密码进行对比
	            //AuthenticationInfo authcInfo =new SimpleAuthenticationInfo("aaa","123","myRealm");
	           //一参 用户名。二参 散列码。三参 盐。四参 realm名
	           AuthenticationInfo authcInfo1 =new SimpleAuthenticationInfo(account, account.getPwd(), ByteSource.Util.bytes(account.getSalt()), "myRealm");
	           return authcInfo1;  
	        }else{
	        	//4.用户不存在返回null
	            return null; 
	            }
	        }
	}
